import storage from "@/utils/storage";
import { getToken } from "@/utils/auth";
import { request } from "http";
import { useChatStore } from "@/store/modules/chat";
// const chatStore = useChatStore();
import { getAnswerList } from "@/api/chat";
import { getAiAnswer } from "../../api/chat";
import config from "@/config/config.json";
export function getMessageList() {
  let messageList = storage.get("messageList");
  if (messageList) {
  } else {
    messageList = [];
  }
  return messageList;
} // wxRequest();

let header = {
  UserName: "sdf",
  Satoken: getToken(),
  "Accept-Language": "zh-CN,zh;q=0.9",
  Accept: "application/json, text/plain, */*",
  "Content-Type": "application/json",

  // "Content-Type": "application/x-www-form-urlencoded",
};
/**
 * @description ai回答内容
 */
export function addAiAnswer(param) {
  let { question } = param;
  let req = {
    chatModel: config.chatModel,
    options: {
      // conversationId: "41df5b1a-64c2-4c63-ad1f-a9c468943413",
      // parentMessageId: "38c71f2e-2f45-4383-8d25-ec796fb22964"
    },
    prompt: question,
    temperature: 0.8,
  };
  return getAiAnswer({
    data: req,
  });
  // uniAddAiAnswer(req);
  // header["content-type"] = "application/x-www-form-urlencoded;charset=utf-8";
  // header["Content-Type"] = "application/json";

  // requestTask.onChunkReceived((res) => {
  //   let { data } = res;
  //   console.log("ai回答", data);
  //   // 接收分片的数据
  //   // handleRequestResolve(data);
  // });
}

export function handleAiResponse(chunk) {
  let { data } = chunk;
  let text = Uint8ArrayToString(data);
  text = decodeURIComponent(escape(text));
  const lastIndex = text.lastIndexOf("\n", text.length - 2);
  let chunk1 = text;
  if (lastIndex !== -1) {
    chunk1 = text.substring(lastIndex);
  } else {
  }
  let res1 = JSON.parse(chunk1);

  console.log("ai回答", res1);
  res1.lastIndex = lastIndex;
  return res1;
}
function Uint8ArrayToString(fileData) {
  let uint8Array = new Uint8Array(fileData);
  let text = "";
  for (let i = 0; i < uint8Array.length; i++) {
    text += String.fromCharCode(uint8Array[i]);
  }
  return text;
}
function uniAddAiAnswer(req) {
  uni.connectSocket({
    url: `${config.siteDomain}/api/chat_message/send`,
    data: req,
    method: "POST",
    header,
    success: (res) => {
      console.log(res.data);
      this.text = "request success";
    },
  });
}
export function addMessage(message) {
  let messageList = getMessageList();
  messageList.unshift(message);
  return message;
}
